function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg); //匹配目标参数
    if (r != null) return (r[2]);
    return null; //返回参数值
}
var orderNum = getUrlParam("orderNum");
var gateway = getUrlParam("gateway");
var payerId = getUrlParam("payerId");
var bindId = null;
var accessBindId = null;
var orderIp = null;
var phone = null;
var token = null;
var time = 0;
var timer = null;

$(function () {
    document.getElementById("select-card").style.display = "block";
    $.getJSON("/thmlfApi/avs/pay/getpayerallbind?gateway=hxtpay" + "&payerId=" + payerId + "&_d=" + Date.parse(new Date()), null, function (r) {
        if (r.code == 200) {
            $.each(r.result, function (index, data) {
                var cardType = data.cardType == "X" ? "信用卡" : "借记卡";
                var item = '<div class="mui-input-row mui-radio mui-left bind-card-item" data-token="'+data.token+'" data-access-bind-id="' + data.accessBindId + '" data-bindid="' + data.bindId + '" data-phone="' + data.phone + '">' +
                    '<label>' + data.cardName + '&nbsp;&nbsp;' + cardType + '&nbsp;&nbsp;' + data.holdName + '&nbsp;&nbsp;' + '尾号' + data.lastFourNum + '</label>' +
                    '<input name="card" type="radio">' +
                    '</div>';
                $(".add-new-card").before(item);
            });
            bindChoose();
        }
    });
    $("#addBindCard").click(function () {
        bindId = null;
        window.location.href = "card-manage.html";
    });
});

// 获取订单信息
function orderInfo() {
    $.ajax({
        url:"/thmlfApi/avs/hxtpay/orderInfo?payerId="+payerId+"&orderNum="+orderNum+"&card="+accessBindId,
        dataType:"JSON",
        success:function (r) {
            if (r.code == 200){
                mui('#forward').popover('toggle');
                $("#bank_num_row").css("display", "block");
                $("#amount").val(r.result.amount + "元");
                $("#order_no").val(r.result.orderNum);
                $("#bank_num_li").val(r.result.cardNum);
            }else if (r.code == 20003){
                openCard();
            }else {
                mui.toast(r.message);
            }
        },
        error:function (e) {
            mui(".confirm-btn").button('reset');
            console.error("request error",e);
            mui.toast("服务器繁忙");
        }
    });
}

// 确认信息，查询开卡
mui(document.body).on('tap','.confirm-btn',function () {
    var that = mui(this);
    console.log("data",accessBindId,token);
    if (accessBindId == null){
        mui.toast("请选择银行卡");
        return;
    }
    if (token == null || token == '' || token == 'null'){
        openCard();
    }else {
        orderInfo();
    }
    // that.button('loading');
    // $.ajax({
    //     url:"/thmlfApi/avs/hxtpay/opencardquery?cashBindId="+accessBindId+"&orderNum="+orderNum+"&payerId="+sessionStorage.getItem('payerId'),
    //     dataType:"JSON",
    //     success:function (r) {
    //         that.button('reset');
    //         if (r.code == 20017){
    //             // 未开卡
    //             mui.confirm("此卡暂未开通快捷支付功能或验证过期，是否前往开通？","提示",["开通","取消"],function (data) {
    //                 if (data.index == 0){
    //                     mui.alert('data');
    //                     openCard();
    //                 }
    //             });
    //         }else if (r.code == 200){
    //             // 已开卡
    //             token = r.result;
    //             orderInfo();
    //         }else {
    //             // 未知错误
    //             mui.alert(r.message);
    //         }
    //     },
    //     error:function (e) {
    //         mui.toast("系统繁忙");
    //         that.button('reset');
    //         console.error("request error",e);
    //     }
    // })
});

// 开卡
function openCard() {
    mui.confirm("此卡未开通快捷功能或认证信息失效，是否前往开通快捷支付功能？如已经开通，请稍后再试。","提示",["确定","取消"],function (e) {
        if (e.index == 0){
            mui(".confirm-btn").button('loading');
            console.log("opencard",accessBindId);
            $.ajax({
                url:"/thmlfApi/avs/hxtpay/opencard?payerId="+sessionStorage.getItem('payerId')+"&cashBindId="+accessBindId+"&orderNum="+orderNum,
                dataType:"JSON",
                success:function (r) {
                    mui(".confirm-btn").button('reset');
                    if (r.code == 200){
                        var html = r.result;
                        html = new Base64().decode(html);
                        // console.log("html",html);
                        document.getElementById('from-hidden').innerHTML = html;
                        console.log("from",document.getElementById('pay_from'));
                        // document.getElementById('pay_from').submit();
                        document.all.pay_form.submit();
                    }else if (r.code == 20003){
                        openCard();
                    }else {
                        mui.alert(r.message);
                    }
                },
                error:function (e) {
                    mui(".confirm-btn").button('reset');
                    console.error("request error",e);
                    mui.toast("服务器繁忙");
                }
            })
        }
    });
}

// 获取短信验证码
mui(document.body).on('tap', '.code-btn', function (e) {
    if (time > 0) {
        return;
    }
    var that = mui(this);
    that.button('loading');
    var params = {
        payerId:payerId,
        token:token,
        orderNum:orderNum,
    };
    $.ajax({
        url:"/thmlfApi/avs/hxtpay/sendsms",
        type:"POST",
        data:JSON.stringify(params),
        contentType: "application/json;charset=utf-8",
        dataType:"JSON",
        success:function (r) {
            that.button('reset');
            if (r.code == 200){
                // 获取成功
                time = 60;
                timer = setInterval(times, 1000);
            }else if (r.code == 20003){
                openCard();
            }else{
                mui.alert(r.message);
            }
        },
        error:function (e) {
            mui.toast("系统繁忙");
            that.button('reset');
            console.error("request error",e);
        }
    });
});

// 确认支付
mui(document.body).on('tap', '.mui-btn-danger', function (e) {
    //	window.location.href = 'pay-success.html';
    var that = mui(this);
    that.button('loading');
    var validateCode = $("#sms_code_input").val().trim();
    if (validateCode == "" || validateCode == null) {
        mui.alert("短信验证码不能为空");
        that.button('reset');
        return false;
    }
    var params = {
        "smsCode": validateCode,
        "orderNum": orderNum,
        "payerId": payerId,
        "token": token
    };
    $.ajax({
        url: "/thmlfApi/avs/hxtpay/payment"+"?_d="+Date.parse(new Date()),
        type: "POST",
        data: JSON.stringify(params),
        dataType: 'json',
        contentType: "application/json;charset=utf-8",
        success: function (r) {
            that.button('reset');
            if (r.code != 200) {
                mui.alert(r.message);
            } else if (r.code == 20003){
                openCard();
            }else{
                mui.alert("支付成功.");
                window.location.href = "pay-success.html"
            }
        },
        error:function (e) {
            mui.alert("服务器繁忙");
            that.button('reset');
        }
    });
});

// 验证码计时器
function times() {
    if (time > 0) {
        $("#sms_code_btn").text(time + 's');
        time--;
    } else {
        clearInterval(timer);
        time = 0;
        $("#sms_code_btn").text('获取');
    }
}

// 选择银行卡
function bindChoose() {
    $(".bind-card-item").click(function () {
        bindId = $(this).attr("data-bindid");
        phone = $(this).attr("data-phone");
        token = $(this).attr("data-token");
        accessBindId = $(this).attr("data-access-bind-id");
    })
}